package com.hayden.fileMonitor;

import com.hayden.fileMonitor.util.JDBCUtils;
import com.hayden.fileMonitor.util.WindowsTools;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.apache.ibatis.session.SqlSessionFactory;
import com.hayden.fileMonitor.pojo.tb_monitorlog;
import com.hayden.fileMonitor.pojo.TcpInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

public class MonitoringService {
    private static int refresh = 0 ;
    private static int operationCount = 0;
    private static String operationIP ;
    private static Boolean ConnectionStatus = false;
    private static SqlSessionFactory sqlSessionFactory;

    private static Logger LOGGER = null;

    static {
        LOGGER = LoggerFactory.getLogger(MonitoringService.class);
    }

    //mybatis
//    static {
//        String resource = "mybatis-config.xml";
//        InputStream inputStream = null;
//        try {
//            inputStream = Resources.getResourceAsStream(resource);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//    }

    public MonitoringService() {
    }

    public static class MyFileAlterationListener implements FileAlterationListener {

        @Override
        public void onStart(FileAlterationObserver fileAlterationObserver) {
            refresh++;
            if (!ConnectionStatus){
                //未连接 进行刷新
                refreshConnectionStatus();
                if(ConnectionStatus){
                    String operationContent = ("检测到远程连接启动：用户 " + operationIP);
                    LOGGER.trace(operationContent);
                    insertLog(operationIP,"-","LinkOpen","启用远程桌面连接");
                }
            }else {
                //连接中
                refreshConnectionStatus();
                if(!ConnectionStatus){
                    String operationContent = ("检测到远程连接断开：用户 " + operationIP);
                    LOGGER.trace(operationContent);
                    insertLog(operationIP,"-","LinkBreak","断开远程桌面连接");
                }
            }


        }
        //文件夹
        @Override
        public void onDirectoryCreate(File directory) {
            operationCount++;
            String operationContent = ("新建文件夹： " + directory.getAbsolutePath());
            LOGGER.trace(operationContent);
            String operationObjectName = operationContent.substring(operationContent.lastIndexOf("\\",operationContent.length())+1);
            System.out.println(operationContent);
            insertLog("-",operationObjectName,"Create",operationContent);
        }

        @Override
        public void onDirectoryChange(File directory) {
            operationCount++;
            String operationContent = ("修改文件夹： " + directory.getAbsolutePath());
            LOGGER.trace(operationContent);
            String operationObjectName = operationContent.substring(operationContent.lastIndexOf("\\",operationContent.length())+1);
            System.out.println(operationContent);
            insertLog("-",operationObjectName,"Change",operationContent);
        }

        @Override
        public void onDirectoryDelete(File directory) {
            operationCount++;
            String operationContent = ("删除文件夹： " + directory.getAbsolutePath());
            LOGGER.trace(operationContent);
            String operationObjectName = operationContent.substring(operationContent.lastIndexOf("\\",operationContent.length())+1);
            System.out.println(operationContent);
            insertLog("-",operationObjectName,"Delete",operationContent);
        }

        //文件
        @Override
        public void onFileCreate(File file) {
            operationCount++;
            String compressedPath = file.getAbsolutePath();
            String operationContent = ("新建文件： " + compressedPath);
            LOGGER.trace(operationContent);
            String operationObjectName = operationContent.substring(operationContent.lastIndexOf("\\",operationContent.length())+1);
            System.out.println(operationContent);
            if(file.canRead()){
                insertLog("-",operationObjectName,"Create",operationContent);
            }
        }

        @Override
        public void onFileChange(File file) {
            operationCount++;
            String compressedPath = file.getAbsolutePath();
            String operationContent = ("修改文件： " + compressedPath);
            LOGGER.trace(operationContent);
            String operationObjectName = operationContent.substring(operationContent.lastIndexOf("\\",operationContent.length())+1);
            System.out.println(operationContent);
            insertLog("-",operationObjectName,"Change",operationContent);
        }

        @Override
        public void onFileDelete(File file) {
            operationCount++;
            String compressedPath = file.getAbsolutePath();
            String operationContent = ("删除文件： " + compressedPath);
            LOGGER.trace(operationContent);
            String operationObjectName = operationContent.substring(operationContent.lastIndexOf("\\",operationContent.length())+1);
            System.out.println(operationContent);
            insertLog("-",operationObjectName,"Delete",operationContent);
        }

        @Override
        public void onStop(FileAlterationObserver fileAlterationObserver) {
            if (!ConnectionStatus){
                //未连接 进行刷新
                refreshConnectionStatus();
                if(ConnectionStatus){
                    String operationContent = ("检测到远程连接启动：用户 " + operationIP);
                    LOGGER.trace(operationContent);
                    insertLog(operationIP,"-","LinkOpen","启用远程桌面连接");
                }
            }else {
                //连接中
                refreshConnectionStatus();
                if(!ConnectionStatus){
                    String operationContent = ("检测到远程连接断开：用户 " + operationIP);
                    LOGGER.trace(operationContent);
                    insertLog(operationIP,"-","LinkBreak","断开远程桌面连接");
                }
            }
        }
    }

    private static void refreshConnectionStatus(){
        try {
            List<TcpInfo>  tcpInfos = WindowsTools.TcpInfoParser();
            String connectionIP = WindowsTools.CheckConnection(tcpInfos);
            if (connectionIP!=null){
                operationIP = connectionIP;
                ConnectionStatus = true;
            }else {
                InetAddress inetAddress = InetAddress.getLocalHost();
                operationIP = inetAddress.getHostAddress();
                ConnectionStatus = false;
            }
        } catch (UnknownHostException e) {
            LOGGER.error("未知host：",e);
        } catch (IOException e) {
            LOGGER.trace("远程连接状态刷新错误：",e);
        }
    }

    public static void insertLog(String OperationUser,String OperationObjectName,String OperationType,String OperationContent) {
        Timestamp createTime = new Timestamp(new Date().getTime());
        tb_monitorlog tb_monitorlog = new tb_monitorlog(createTime,OperationUser,OperationObjectName,OperationType,OperationContent);
        //mybatis
//        SqlSession sqlSession = sqlSessionFactory.openSession();
//        sqlSession.insert("sql.insertOne",tb_monitorlog);
//        sqlSession.commit();
//        sqlSession.close();
        try {
            JDBCUtils.insertOne(tb_monitorlog);
        } catch (SQLException e) {
            LOGGER.error("数据库插入错误：",e);
        }
    }

}